package com.qwc.blog.controller.back;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qwc.blog.common.validate.IdValid;
import com.qwc.blog.entity.Config;
import com.qwc.blog.entity.vo.config.AddConfigDto;
import com.qwc.blog.entity.vo.config.ConfigListReqDto;
import com.qwc.blog.security.service.LoginService;
import com.qwc.blog.service.IConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import static com.qwc.blog.common.constant.ResponseConstant.*;

/**
 * <p>
 * 配置表 前端控制器
 * </p>
 *
 * @author qwc
 * @since 2021-11-08
 */
@RestController
@RequestMapping("/blog/config")
public class ConfigController {

    @Autowired
    private IConfigService configService;

    @GetMapping("/list")
    public ResponseEntity<Object> listConfig(ConfigListReqDto dto) {
        Map<String, Object> map = new HashMap<>(4);
        Page<Config> postsPage = configService.getConfigList(dto);
        map.put(ROWS, postsPage.getRecords());
        map.put(TOTAL, postsPage.getTotal());
        return ResponseEntity.ok(map);
    }

    @PostMapping
    public ResponseEntity<Object> addConfig(@Validated @RequestBody AddConfigDto dto) {
        configService.addConfig(dto);
        return ResponseEntity.ok().build();
    }

    @GetMapping("/{id}")
    public ResponseEntity<Object> getConfig(@PathVariable Integer id) {
        Map<String, Object> map = new HashMap<>(4);
        Config byId = configService.getById(id);
        map.put(DATA, byId);
        return ResponseEntity.ok(map);
    }

    @PutMapping
    public ResponseEntity<Object> updateConfig(@Validated(IdValid.class) @RequestBody AddConfigDto dto) {
        configService.updateConfig(dto);
        return ResponseEntity.ok().build();
    }

    @PutMapping("/update/status")
    public ResponseEntity<Object> updateConfigStatus(Integer id, String status) {
        configService.update(Wrappers.<Config>lambdaUpdate().set(Config::getStatus, status).eq(Config::getId, id));
        return ResponseEntity.ok().build();
    }

    @DeleteMapping("/{configId}")
    public ResponseEntity<Object> deleteConfig(@PathVariable Integer[] configId) {
        configService.removeByIds(Arrays.asList(configId));
        return ResponseEntity.ok().build();
    }

}
